package com.gupaoedu.spring.pattern.proxy.custom;

import java.io.*;

public class GPClassLoader extends ClassLoader{

    private File classPathFile;

    public GPClassLoader () {

        String classPath = GPClassLoader.class.getResource("").getPath();
        this.classPathFile = new File(classPath);
    }


    protected Class<?> findClass (String name ) throws  ClassNotFoundException {


        String className = GPClassLoader.class.getPackage().getName() + "." + name;

        if (classPathFile != null ) {

            File clasSFile = new File(classPathFile,name.replaceAll("\\.","/") + ".class");

            if ( clasSFile.exists() ) {

                FileInputStream in = null;
                ByteArrayOutputStream out = null;

                try {

                    in = new FileInputStream(clasSFile);
                    out = new ByteArrayOutputStream();
                    byte [] buff = new byte[1024];
                    int len = 0;
                    while ( (len = in.read(buff)) != -1 ) {
                        out.write(buff, 0, len);
                    }

                    return defineClass(className, out.toByteArray(), 0, out.size());



                } catch ( Exception e) {

                    e.printStackTrace();
                }
                finally {


                    try {
                        if ( null != in ) {
                            in.close();
                        }

                        if ( null != out ) {

                            out.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }




        }
        return  null;

    }

}
